package com.spdzen.controller.admin;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.spdzen.support.LogUtils;
import com.spdzen.support.UploadFile;
import com.spdzen.support.UploadFileUtils;
import com.spdzen.support.result.JsonResult;

@Controller
@RequestMapping("/admin/upload")
public class UploadAdminController {

	@RequestMapping(path = { "/file.do" }, method = { RequestMethod.POST })
	@ResponseBody
	public JsonResult uploadFile(@RequestParam(value = "uploadfile", required = false) MultipartFile uploadFile, HttpServletRequest request) {
		if (uploadFile == null) {
			return JsonResult.error();
		}

		JsonResult result = null;
		try {
			result = JsonResult.success(UploadFileUtils.saveToTemp(uploadFile, request));
		} catch (Exception e) {
			LogUtils.getLogger().error("", e);
			result = JsonResult.error("上传失败！");
		}

		return result;
	}

	@RequestMapping(path = { "/wangEditorImage.do" }, method = { RequestMethod.POST })
	@ResponseBody
	public String uploadWangEditorImage(@RequestParam(value = "uploadfile", required = false) MultipartFile uploadFile, HttpServletRequest request) {
		if (uploadFile == null) {
			return "error|上传失败！";
		}

		try {
			long size = uploadFile.getSize();
			if (size > 2097152L) {
				return "errlr|图片太大，不得超过2M。";
			}

			String extension = FilenameUtils.getExtension(uploadFile.getOriginalFilename()).toLowerCase();
			if (extension.equals("png") || extension.equals("jpg") || extension.equals("jpeg") || extension.equals("bmp") || extension.equals("gif")) {
				UploadFile uf = UploadFileUtils.saveToNewsImage(uploadFile, request);
				return request.getContextPath() + uf.getUrl();
			} else {
				return "error|请上传图片，只支持png/jpg/bmp/gif格式。";
			}
		} catch (Exception e) {
			LogUtils.getLogger().error("", e);
			return "error|上传失败！";
		}
	}
}
